#include <stdlib.h>
#include <stdio.h>
#include <nds.h>

// common headers
#include "common.h"

// local headers

#include "keysinstance.h"

void ki_scanKeys(sKeysInstance *ki) {
    if(!ki) return;

    ki->keysold=ki->keys;
    ki->keys=keysCurrent();

    if(ki->delay) {
        if(ki->keys!=ki->keysold) {
            ki->count=ki->delay;
            ki->keysrepeat=ki_keysDown(ki);
        }
        ki->count--;
        if(!ki->count) {
            ki->count=ki->repeat;
            ki->keysrepeat=ki->keys;
        }
    }
}

uint32 ki_keysHeld(sKeysInstance *ki) {
    return ki?(ki->keys):0;
}

uint32 ki_keysDown(sKeysInstance *ki) {
    return ki?(ki->keys&~ki->keysold):0;
}

uint32 ki_keysDownRepeat(sKeysInstance *ki) {
    if(!ki) return 0;

    uint32 tmp=ki->keysrepeat;
    ki->keysrepeat=0;
    return tmp;
}

void ki_keysSetRepeat(sKeysInstance *ki, u8 setDelay, u8 setRepeat) {
    if(!ki) return;

    ki->delay=setDelay;
    ki->repeat=setRepeat;
    ki->count=setDelay;
    ki->keysrepeat=0;
}

uint32 ki_keysUp(sKeysInstance *ki) {
    return ki?((ki->keys^ki->keysold)&(~ki->keys)):0;
}

